<!-- mqtt -->
<template>
  <div></div>
</template>

<script>
import mqtt from "mqtt"
import lockr from "lockr"
import { mapState } from "vuex"
import JSONBigInt from "json-bigint"
export default {
  name: "mqttConnect",
  data() {
    return {
      connection: {
        protocol: "ws",
        // eslint-disable-next-line no-undef
        host: websocketUrl,
        // ws: 8083; wss: 8084
        // eslint-disable-next-line no-undef
        port: websocketPort,
        endpoint: "/mqtt",
        // for more options, please refer to https://github.com/mqttjs/MQTT.js#mqttclientstreambuilder-options
        clean: true,
        connectTimeout: 30 * 1000, // ms
        reconnectPeriod: 4000, // ms
        clientId:
          "emqx_vue_" +
          Math.random().toString(16).substring(2, 8) +
          lockr.get("userInfo").userId
      },
      subscription: {
        topic: "topic/mqttx",
        qos: 0
      },
      publish: {
        topic: "topic/browser",
        qos: 0,
        payload: '{ "msg": "Hello, I am browser." }'
      },
      receiveNews: "",
      qosList: [0, 1, 2],
      client: {
        connected: false
      },
      subscribeSuccess: false,
      connecting: false,
      retryTimes: 0
    }
  },

  computed: {
    ...mapState({
      groupList: (state) => state.groupList,
      userId: (state) => state.userInfo.userId
    })
  },

  mounted() {
    this.createConnection()
  },

  methods: {
    initData() {
      this.client = {
        connected: false
      }
      this.retryTimes = 0
      this.connecting = false
      this.subscribeSuccess = false
    },
    handleOnReConnect() {
      this.retryTimes += 1
      if (this.retryTimes > 5) {
        try {
          this.client.end()
          this.initData()
          this.$message.error("Connection maxReconnectTimes limit, stop retry")
        } catch (error) {
          this.$message.error(error.toString())
        }
      }
    },
    createConnection() {
      try {
        this.connecting = true
        const { protocol, host, port, endpoint, ...options } = this.connection
        const connectUrl = `${protocol}://${host}:${port}${endpoint}`
        this.client = mqtt.connect(connectUrl, options)
        this.$store.commit("setClient", this.client)
        let _this = this
        if (this.client.on) {
          this.client.on("connect", function () {
            _this.connecting = false
            _this.doSubscribe()
            console.log("Connection succeeded!")
          })
          this.client.on("reconnect", this.handleOnReConnect)
          this.client.on("error", function (error) {
            console.log("Connection failed", error)
          })
          this.client.subscribe(`chat/notice/monster02`)
          setTimeout(() => {
            this.client.publish("chat/notice/monster01", "Hello mqtt")
          }, 5000)
          this.client.on("message", function (topic, message) {
            console.log(
              `Received message: ${message.toString()} on topic: ${topic}`
            )
            _this.receiveNews = _this.receiveNews.concat(message)
            let msg = JSONBigInt.parse(message)
            if (msg.receiverId) msg.receiverId = msg.receiverId.toString()
            let actionInfo = {
              topic,
              info: msg
            }
            _this.$store.commit("catchMqttAction", actionInfo)
          })

          this.client.on("offline", function () {
            _this.$store.state.mqStatus = false
          })
        }
      } catch (error) {
        this.connecting = false
        console.log("mqtt.connect error", error)
      }
    },
    doSubscribe() {
      // ACTION("im/action", "动作"), SIMPLE("im/simple", "单聊"), GROUP("im/group", "群聊");
      this.$store.dispatch("doSubscribe")
    }
  }
}
</script>
<style lang="less" scoped></style>
